<template>
  <div class="control-item">
    <label v-if="type !== 'checkbox' || !labelAfter">
      {{ label }}{{ type !== 'select' && value !== undefined ? ': ' + value : '' }}
    </label>
    <component 
      :is="getComponentType()"
      :type="type === 'select' ? undefined : type"
      :min="min"
      :max="max"
      :step="step"
      :value="value"
      :checked="type === 'checkbox' ? value : undefined"
      @input="handleInput"
      @change="handleChange"
    >
      <slot v-if="type === 'select'">
        <!-- Options will be placed here by parent component -->
      </slot>
    </component>
    <label v-if="type === 'checkbox' && labelAfter" class="checkbox-label">
      {{ label }}
    </label>
  </div>
</template>

<script>
export default {
  name: 'ControlItem',
  props: {
    type: {
      type: String,
      default: 'text'
    },
    label: {
      type: String,
      required: true
    },
    labelAfter: {
      type: Boolean,
      default: false
    },
    value: {
      type: [String, Number, Boolean],
      default: undefined
    },
    min: {
      type: [String, Number],
      default: undefined
    },
    max: {
      type: [String, Number],
      default: undefined
    },
    step: {
      type: [String, Number],
      default: undefined
    }
  },
  emits: ['update:value', 'change', 'input'],
  methods: {
    getComponentType() {
      switch (this.type) {
        case 'text':
        case 'range':
        case 'checkbox':
          return 'input';
        case 'select':
          return 'select';
        default:
          return 'input';
      }
    },
    handleInput(event) {
      this.emitValue(event);
    },
    handleChange(event) {
      this.emitValue(event);
    },
    emitValue(event) {
      let value;
      
      if (this.type === 'checkbox') {
        value = event.target.checked;
      } else if (this.type === 'range' || this.type === 'number') {
        value = this.isNumeric(event.target.value) ? Number(event.target.value) : event.target.value;
      } else {
        value = event.target.value;
      }
      
      this.$emit('update:value', value);
      // For backward compatibility with existing code using @input or @change
      this.$emit('input', { target: { value } });
      this.$emit('change', { target: { value } });
    },
    isNumeric(value) {
      return !isNaN(parseFloat(value)) && isFinite(value);
    }
  }
};
</script>

<style scoped>
.control-item {
  margin-bottom: 10px;
}

.control-item label {
  display: block;
  margin-bottom: 5px;
  font-size: 12px;
}

.control-item input[type="range"] {
  width: 100%;
}

.control-item select,
.control-item input[type="text"] {
  width: 100%;
  padding: 5px;
  border-radius: 3px;
  border: 1px solid #666;
  background: #333;
  color: white;
}

.control-item .checkbox-label {
  display: inline;
  margin-left: 5px;
  user-select: none;
}
</style>